package com.fruit.controller.wap.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.apache.commons.lang.StringUtils;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.StockRecordCourier;
import com.fruit.pojo.user.SysUser;
import com.fruit.service.order.OrderManager;
import com.fruit.service.user.SysRoleManager;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

@Controller
@RequestMapping(value = "/wap/order")
public class OrderController extends BaseController {

	@Resource(name = "orderService")
	private OrderManager orderService;

	@Autowired
	private SysRoleManager sysRoleService;

	// 查询订单列表
	@RequestMapping(value = "/getOrderList", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView getOrderList(Page page, HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "查询订单列表");
		ModelAndView mv = this.getModelAndView();
		try {
			// 获取后台的登录人
			SysUser user = (SysUser) session.getAttribute("sysUser");
//			SysUser user =new SysUser();
//			user.setRoleId("1");
//			user.setUserId("1");
			if (user != null) {
				if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_view")) {// 订单查看权限
					page.getParams().put("userId", user.getUserId());
					page.getParams().put("state", request.getParameter("state"));
					String state = request.getParameter("state");
					if (StringUtils.isEmpty(state)) {
						mv.addObject("result", this.initResult(ResultInfo.ERROR, "parame-error", "参数错误!"));
					}
					page.getParams().put("isAllView",
							sysRoleService.getQxNameCnt(user.getRoleId(), "all_view") ? "1" : "0");
					List<Order> orders = orderService.getOrderList(page);
					if (orders!=null ){
						if(orders.size()>0){
						Map<String, Order> orderMap = new TreeMap<String, Order>(Collections.reverseOrder());
						Integer sum = 0;// 用于一个订单的商品数量的计数
						for (Order order : orders) {
							if ("00".equals(order.getState())) {
								order.setStateName("未付款");
							} else if ("02".equals(order.getState())) {
								order.setStateName("待发货");
							} else if ("03".equals(order.getState())) {
								order.setStateName("待收货");
							} else if ("04".equals(order.getState())) {
								order.setStateName("已完成");
							} else if ("05".equals(order.getState())) {
								order.setStateName("已取消");
							} else if ("06".equals(order.getState())) {
								order.setStateName("已退款");
							}
							Order goods = new Order();
							goods.setGoods_id(order.getGoods_id());
							goods.setGoodsThumb(order.getGoodsThumb());
							goods.setTitle(order.getTitle());
							goods.setTradePrice(order.getTradePrice());
							goods.setNumber(order.getNumber());
							goods.setBuyUnit(order.getBuyUnit());
							if (!orderMap.containsKey(order.getId() + "s")) {
								Order good = new Order();
								String codePre = (String) order.getCodePre();
								String codeSuf = (String) order.getCodeSuf();
								good.setOrderCode(codePre + order.getId() + codeSuf);
								good.setId(order.getId());
								good.setState(order.getState());
								good.setStateName(order.getStateName());
								good.setRealPrice(order.getRealPrice());
								good.setRefundState(order.getRefundState());
								good.getGoodsList().add(goods);
								sum = 1;
								good.setSum(sum);
								orderMap.put(Long.toString(order.getId()) + "s", good);
							} else {
								Order o = (Order) orderMap.get(Long.toString(order.getId()) + "s");
								sum = o.getSum() + 1;
								o.setSum(sum);
								o.getGoodsList().add(goods);
							}
						}
						Collection<Order> valueCollection = orderMap.values();
						List<Order> resOrderList = new ArrayList<Order>(valueCollection);
						mv.addObject("orderList", resOrderList);
						mv.addObject("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
						mv.addObject("msg", "00");
						mv.addObject("size",orders.size());
						}else{
							mv.addObject("msg", "没有订单!");
						}
					}else{
						mv.addObject("msg", "没有订单!");
					} 
				} else {
					mv.addObject("msg", "没有权限!");
				}
			} else {
				mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-USERID", "没有登录"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			mv.addObject("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		mv.setViewName("order/order_list");
		this.logAfter(logger);
		return mv;
	}
	
	// 查询订单列表
		@RequestMapping(value = "/getOrderListPage", method = { RequestMethod.GET, RequestMethod.POST })
		@ResponseBody
		public Map<String,Object> getOrderListPage(Page page, HttpServletRequest request, HttpSession session) {
			this.logBefore(logger, "查询订单列表");
			List<Order> resOrderList = null; 
			Map<String,Object> resMap = new HashMap<String, Object>();
			try {
				// 获取后台的登录人
				SysUser user = (SysUser) session.getAttribute("sysUser");
				if (user != null) {
					if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_view")) {// 订单查看权限
						page.getParams().put("userId", user.getUserId());
						page.getParams().put("state", request.getParameter("state"));
						String state = request.getParameter("state");
						page.getParams().put("isAllView",
								sysRoleService.getQxNameCnt(user.getRoleId(), "all_view") ? "1" : "0");
						page.setStart((page.getPage()-1) * page.getShowNumber());
						List<Order> orders = orderService.getOrderList(page);
						if (orders!=null ){
							if(orders.size()>0){
							Map<String, Order> orderMap = new TreeMap<String, Order>(Collections.reverseOrder());
							Integer sum = 0;// 用于一个订单的商品数量的计数
							for (Order order : orders) {
								if ("00".equals(order.getState())) {
									order.setStateName("未付款");
								} else if ("02".equals(order.getState())) {
									order.setStateName("待发货");
								} else if ("03".equals(order.getState())) {
									order.setStateName("待收货");
								} else if ("04".equals(order.getState())) {
									order.setStateName("已完成");
								} else if ("05".equals(order.getState())) {
									order.setStateName("已取消");
								} else if ("06".equals(order.getState())) {
									order.setStateName("已退款");
								}
								Order goods = new Order();
								goods.setGoods_id(order.getGoods_id());
								goods.setGoodsThumb(order.getGoodsThumb());
								goods.setTitle(order.getTitle());
								goods.setTradePrice(order.getTradePrice());
								goods.setNumber(order.getNumber());
								goods.setBuyUnit(order.getBuyUnit());
								if (!orderMap.containsKey(order.getId() + "s")) {
									Order good = new Order();
									String codePre = (String) order.getCodePre();
									String codeSuf = (String) order.getCodeSuf();
									good.setOrderCode(codePre + order.getId() + codeSuf);
									good.setId(order.getId());
									good.setState(order.getState());
									good.setStateName(order.getStateName());
									good.setRealPrice(order.getRealPrice());
									good.setRefundState(order.getRefundState());
									good.getGoodsList().add(goods);
									sum = 1;
									good.setSum(sum);
									orderMap.put(Long.toString(order.getId()) + "s", good);
								} else {
									Order o = (Order) orderMap.get(Long.toString(order.getId()) + "s");
									sum = o.getSum() + 1;
									o.setSum(sum);
									o.getGoodsList().add(goods);
								}
							}
							Collection<Order> valueCollection = orderMap.values();
							resOrderList = new ArrayList<Order>(valueCollection);
							resMap.put("resOrderList", resOrderList);
							resMap.put("size", resOrderList.size());
							}else{
								resMap.put("resOrderList", resOrderList);
								resMap.put("size", 0);
							}
						}else{
							resMap.put("resOrderList", resOrderList);
							resMap.put("size", 0);
						}
					} 
				} 

			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
			}
			
			this.logAfter(logger);
			return resMap;
		}

	// 查询订单详情
	@RequestMapping(value = "/getOrderDetails", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ModelAndView getOrderDetails(HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "查询订单列表");
		ModelAndView mv = this.getModelAndView();
		Map<String, Object> resMap = new HashMap<String, Object>();
		String oid = request.getParameter("oid");
		String userId = (String) session.getAttribute("userId");
		try {
			SysUser user = (SysUser) session.getAttribute("sysUser");
			if (user != null) {
				if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_view")) {// 订单查看权限
					List<Order> orderDetail = orderService.getOrderDetails(oid);
					mv.setViewName("order/order_detail");
					mv.addObject("orderDetail", orderDetail.get(0));
				} else {
					mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-ROLE", "没有权限"));
				}
			} else {
				mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-USERID", "没有登录"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			mv.addObject("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return mv;
	}

	// 添加司机页面
	@RequestMapping(value = "/getCourier", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ModelAndView getCourier(HttpServletRequest request, HttpSession session) throws Exception {
		ModelAndView mv = this.getModelAndView();
		SysUser user = (SysUser) session.getAttribute("sysUser");
		if (user != null) {
			if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_update")) {// 订单修改权限
				String ordId = request.getParameter("ordId");
				String state = request.getParameter("state");
				mv.setViewName("order/transport");
				mv.addObject("ordId", ordId);
				mv.addObject("state", state);
			} else {
				mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-ROLE", "没有权限"));
			}
		} else {
			mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-USERID", "没有登录"));
		}
		return mv;
	}

	// 添加司机
	@RequestMapping(value = "/addCourier", method = { RequestMethod.GET, RequestMethod.POST })
	public String addCourier(HttpServletRequest request, HttpSession session) throws Exception {
		ModelAndView mv = this.getModelAndView();
		SysUser user = (SysUser) session.getAttribute("sysUser");
		String res = "error";
		String ordId = request.getParameter("ordId");
		String state = request.getParameter("state");
		if (user != null) {
			if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_update")) {// 订单修改权限
				
				String linkmanName = request.getParameter("linkmanName");
				String linkmanPhone = request.getParameter("linkmanPhone");
				String plateNumber = request.getParameter("plateNumber");
				String remark = request.getParameter("remark");
				StockRecordCourier sc = new StockRecordCourier();
				sc.setLinkmanName(linkmanName);
				sc.setLinkmanPhone(linkmanPhone);
				sc.setPlate_Number(plateNumber);
				sc.setRemark(remark);
				if ("02".equals(state)) {
					try {
						orderService.saveRecordCourier(sc);
						res = "sucess";
					} catch (Exception e) {
						// TODO: handle exception
						res = "error";
					}
					// 查询版本号
					Map<String, Object> versionMap = orderService.getVersion(ordId);
					int version = (int) versionMap.get("version");
					if (StringUtils.isNotBlank(ordId)) {
						Order order = new Order();
						order.setId(Integer.parseInt(ordId));
						order.setState("03");
						order.setVersion(version);
						orderService.updateOrderState(order);
					}
				}
			} else {
				return "redirect:/wap/order/getCourier?ordId="+ordId+"&state="+state+"&msg=你没有权限!";
			}
		}
		if(res=="error"){
			return "redirect:/wap/order/getCourier?ordId="+ordId+"&state="+state;
		} else {
			return "redirect:/wap/order/getOrderList?state="+state;
		}
		
	}

	// 确认收货
	@RequestMapping(value = "/updateState", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateState(HttpServletRequest request, HttpSession session) throws Exception {
		ModelAndView mv = this.getModelAndView();
		SysUser user = (SysUser) session.getAttribute("sysUser");
		String ordId = request.getParameter("ordId");
		String state = request.getParameter("state");
		if (user != null) {
			if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_update")) {// 订单修改权限
				try {
					// 查询版本号
					Map<String, Object> versionMap = orderService.getVersion(ordId);
					int version = (int) versionMap.get("version");
					if (StringUtils.isNotBlank(state) && StringUtils.isNotBlank(ordId)) {
						Order order = new Order();
						order.setId(Integer.parseInt(ordId));
						if ("03".equals(state)) {
							order.setState("04");
						}
						order.setVersion(version);
						orderService.updateOrderState(order);
					}
				} catch (Exception e) {
					state = "04";
				}
			}
		}
		return "redirect:/wap/order/getOrderList?state="+state;
	}

	// 搜索订单
	@RequestMapping(value = "/search", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ModelAndView search(Page page, HttpServletRequest request, HttpSession session) {
		this.logBefore(logger, "搜索订单");
		ModelAndView mv = this.getModelAndView();
		try {
			// 获取后台的登录人
			SysUser user = (SysUser) session.getAttribute("sysUser");
			if (user != null) {
				if (sysRoleService.getQxNameCnt(user.getRoleId(), "order_view")) {// 订单查看权限
					page.getParams().put("userId", user.getUserId());
					page.getParams().put("isAllView",
							sysRoleService.getQxNameCnt(user.getRoleId(), "all_view") ? "1" : "0");
					page.getParams().put("keywords", request.getParameter("keywords"));
					List<Order> orders = orderService.search(page);
					if (orders.size() > 0) {
						Map<String, Order> orderMap = new TreeMap<String, Order>(Collections.reverseOrder());
						Integer sum = 0;// 用于一个订单的商品数量的计数
						for (Order order : orders) {
							if ("00".equals(order.getState())) {
								order.setStateName("未付款");
							} else if ("02".equals(order.getState())) {
								order.setStateName("待发货");
							} else if ("03".equals(order.getState())) {
								order.setStateName("待收货");
							} else if ("04".equals(order.getState())) {
								order.setStateName("已完成");
							} else if ("05".equals(order.getState())) {
								order.setStateName("已取消");
							} else if ("06".equals(order.getState())) {
								order.setStateName("已退款");
							}
							Order goods = new Order();
							goods.setGoods_id(order.getGoods_id());
							goods.setGoodsThumb(order.getGoodsThumb());
							goods.setTitle(order.getTitle());
							goods.setTradePrice(order.getTradePrice());
							goods.setNumber(order.getNumber());
							goods.setBuyUnit(order.getBuyUnit());
							if (!orderMap.containsKey(order.getId() + "s")) {
								Order good = new Order();
								String codePre = (String) order.getCodePre();
								String codeSuf = (String) order.getCodeSuf();
								good.setOrderCode(codePre + order.getId() + codeSuf);
								good.setId(order.getId());
								good.setState(order.getState());
								good.setStateName(order.getStateName());
								good.setRealPrice(order.getRealPrice());
								good.setRefundState(order.getRefundState());
								good.getGoodsList().add(goods);
								sum = 1;
								good.setSum(sum);
								orderMap.put(Long.toString(order.getId()) + "s", good);
							} else {
								Order o = (Order) orderMap.get(Long.toString(order.getId()) + "s");
								sum = o.getSum() + 1;
								o.setSum(sum);
								o.getGoodsList().add(goods);
							}
						}
						Collection<Order> valueCollection = orderMap.values();
						List<Order> resOrderList = new ArrayList<Order>(valueCollection);
						mv.addObject("orderList", resOrderList);
						mv.addObject("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
						mv.setViewName("order/search");
					} else {
						mv.addObject("result", this.initResult(ResultInfo.SUCCESS, "NO-ORDER", "未产生订单!"));
					}
				} else {
					mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-ROLE", "没有权限"));
				}
			} else {
				mv.addObject("result", this.initResult(ResultInfo.ERROR, "NO-USERID", "没有登录"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			mv.addObject("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return mv;
	}
}
